import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter/services.dart'; // Added for SystemUiOverlayStyle

import 'index.dart';

class FundsPage extends GetView<FundsController> {
  const FundsPage({super.key});

  // 构建顶部积分信息区域
  Widget _buildPointsInfo() {
    return GetBuilder<FundsController>(
      builder: (controller) {
        final levelInfo = controller.levelInfo;
        final isMaxLevel = levelInfo['isMaxLevel'] as bool;
        
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 30),
          decoration: BoxDecoration(
            gradient: LinearGradient(
              colors: [Color(0xFFD46A6A), Color(0xFFC25555)],
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
            ),
          ),
          child: Row(
            children: [
              // 金币图标
              Container(
                width: 70,
                height: 70,
                decoration: BoxDecoration(
                  shape: BoxShape.circle,
                  color: Colors.amber[100],
                  boxShadow: [
                    BoxShadow(
                      color: Colors.black.withOpacity(0.1),
                      blurRadius: 10,
                      spreadRadius: 1,
                    ),
                  ],
                ),
                child: Center(
                  child: Text(
                    '\$',
                    style: TextStyle(
                      fontSize: 40,
                      fontWeight: FontWeight.bold,
                      color: Colors.amber,
                    ),
                  ),
                ),
              ),
              SizedBox(width: 20),
              // 积分和等级信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 用户积分显示
                    Text(
                      controller.isLoadingUserPoints.value 
                          ? '加载中...' 
                          : '${controller.userPoints}积分',
                      style: TextStyle(
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                        color: Colors.white,
                      ),
                    ),
                    SizedBox(height: 5),
                    Row(
                      children: [
                        // 等级显示
                        Container(
                          padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                          decoration: BoxDecoration(
                            color: Colors.white.withOpacity(0.2),
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Text(
                            'Lv${levelInfo['currentLevel']}',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.white,
                            ),
                          ),
                        ),
                        SizedBox(width: 10),
                        Expanded(
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.end,
                            children: [
                              // 进度条
                              ClipRRect(
                                borderRadius: BorderRadius.circular(5),
                                child: LinearProgressIndicator(
                                  value: levelInfo['progress'] as double,
                                  backgroundColor: Colors.white.withOpacity(0.2),
                                  valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                                  minHeight: 6,
                                ),
                              ),
                              SizedBox(height: 4),
                              // 进度文字
                              Text(
                                isMaxLevel 
                                    ? '已达到最高等级' 
                                    : '升级所需积分 ${levelInfo['neededPoints']}',
                                style: TextStyle(
                                  fontSize: 11,
                                  color: Colors.white,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 构建积分充值选项
  Widget _buildRechargeOptions() {
    return Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),
              child: Row(
                children: [
                  Text(
                    '积分加油站',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  Spacer(),
                  // 加载状态指示器
                  GetBuilder<FundsController>(
                    builder: (ctrl) => ctrl.isLoading
                        ? SizedBox(
                            width: 16,
                            height: 16,
                            child: CircularProgressIndicator(
                              strokeWidth: 2,
                              valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
                            ),
                          )
                        : SizedBox.shrink(),
                  ),
                ],
              ),
            ),
            
            // 套餐列表
            GetBuilder<FundsController>(
              builder: (ctrl) {
                if (ctrl.isLoading && ctrl.packagesData.isEmpty) {
                  return Padding(
                    padding: EdgeInsets.symmetric(vertical: 50),
                    child: Center(
                      child: Column(
                        children: [
                          CircularProgressIndicator(
                            valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
                          ),
                          SizedBox(height: 10),
                          Text(
                            '正在加载积分套餐...',
                            style: TextStyle(color: Colors.grey),
                          ),
                        ],
                      ),
                    ),
                  );
                }

                if (ctrl.packagesData.isEmpty) {
                  return Padding(
                    padding: EdgeInsets.symmetric(vertical: 50),
                    child: Center(
                      child: Column(
                        children: [
                          Icon(Icons.shopping_cart_outlined, size: 48, color: Colors.grey[400]),
                          SizedBox(height: 10),
                          Text(
                            '暂无积分套餐',
                            style: TextStyle(color: Colors.grey),
                          ),
                          SizedBox(height: 10),
                          ElevatedButton(
                            onPressed: () => ctrl.loadPointsPackages(),
                            child: Text('重新加载'),
                          ),
                        ],
                      ),
                    ),
                    );
                }

                return Container(
                  height: 100, // 减少高度：140 → 100
                  padding: EdgeInsets.symmetric(horizontal: 15),
                  child: ListView.builder(
                    scrollDirection: Axis.horizontal, // 横向滚动
                    physics: BouncingScrollPhysics(),
                    itemCount: ctrl.packagesData.length > 4 ? 4 : ctrl.packagesData.length, // 最多显示4个
                    itemBuilder: (context, index) {
                  try {
                    final package = ctrl.packagesData[index];
                    final isSelected = ctrl.selectedIndex == index;
                  
                  return GestureDetector(
                    onTap: () => ctrl.selectPackage(index),
                    child: Container(
                      width: 110, // 减小宽度：140 → 110
                      margin: EdgeInsets.only(right: 12), // 右边距分隔
                      decoration: BoxDecoration(
                        border: Border.all(
                          color: isSelected 
                              ? Color(0xFFE33641) 
                              : (package.isPopular 
                                  ? Colors.amber[300]! 
                                  : Colors.grey[300]!),
                          width: isSelected ? 2 : 1,
                        ),
                        borderRadius: BorderRadius.circular(8),
                        color: isSelected 
                            ? Color(0xFFE33641).withOpacity(0.1) 
                            : Colors.white,
                      ),
                      child: Stack(
                        children: [
                          // 热门标签
                          if (package.isPopular)
                            Positioned(
                              top: -1,
                              right: -1,
                              child: Container(
                                padding: EdgeInsets.symmetric(horizontal: 4, vertical: 1),
                                decoration: BoxDecoration(
                                  color: Colors.red,
                                  borderRadius: BorderRadius.only(
                                    topRight: Radius.circular(8),
                                    bottomLeft: Radius.circular(6),
                                  ),
                                ),
                                child: Text(
                                  '热门',
                                  style: TextStyle(
                                    color: Colors.white,
                                    fontSize: 8,
                                    fontWeight: FontWeight.bold,
                                  ),
                                ),
                              ),
                            ),
                          
                          // 主要内容
                          Padding(
                            padding: EdgeInsets.all(6.0),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                // 积分数量
                                Text(
                                  package.formattedPoints,
                                  style: TextStyle(
                                    fontSize: 14,
                                    fontWeight: FontWeight.bold,
                                    color: isSelected ? Color(0xFFE33641) : Colors.black87,
                                  ),
                                  textAlign: TextAlign.center,
                                ),
                                SizedBox(height: 4),
                                
                                // 价格显示
                                Text(
                                  package.formattedPrice,
                                  style: TextStyle(
                                    fontSize: 16,
                                    color: isSelected ? Color(0xFFE33641) : Color(0xFFE33641),
                                    fontWeight: FontWeight.bold,
                                  ),
                                  textAlign: TextAlign.center,
                                ),
                                
                                // 删除折扣信息显示
                                SizedBox(height: 4),
                                
                                // 套餐描述
                                SizedBox(height: 2),
                                Text(
                                  package.packageDescription,
                                  style: TextStyle(
                                    fontSize: 10,
                                    color: Colors.grey[600],
                                  ),
                                  textAlign: TextAlign.center,
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ],
                            ),
                          ),
                          
                          // 选中状态指示器
                          if (isSelected)
                            Positioned(
                              bottom: 3,
                              right: 3,
                              child: Icon(
                                Icons.check_circle,
                                color: Color(0xFFE33641),
                                size: 12,
                              ),
                            ),
                        ],
                      ),
                    ),
                  );
                  } catch (e) {
                    return Container(
                      width: 110,
                      margin: EdgeInsets.only(right: 12),
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.red),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: Center(
                        child: Text(
                          '错误',
                          style: TextStyle(color: Colors.red, fontSize: 10),
                        ),
                      ),
                    );
                  }
                },
              ),
                );
              },
            ),
            
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 20, vertical: 10),
              child: Text(
                '*实际不可退款，请确认您的充值信息。',
                style: TextStyle(
                  fontSize: 11,
                  color: Colors.grey,
                ),
              ),
            ),
          ],
        );
  }

  // 主视图
  Widget _buildView() {
    return Stack(
      children: [
        // 顶部积分信息
        Column(
          children: [
            _buildPointsInfo(),
          ],
        ),
        // 白色内容区域，使用Stack和Positioned避免负margin
        Positioned(
          top: 160, // 调整此值以控制白色容器与红色背景的重叠程度
          left: 0,
          right: 0,
          bottom: 0,
          child: Column(
            children: [
              Expanded(
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.only(
                      topLeft: Radius.circular(20),
                      topRight: Radius.circular(20),
                    ),
                  ),
                  child: Column(
                    children: [
                      // 积分加油站 - 固定区域
                      _buildRechargeOptions(),
                      // 积分变更历史 - 可滚动区域
                      Expanded(
                        child: _buildScrollableHistoryRecords(),
                      ),
                    ],
                  ),
                ),
              ),
              // 确认支付按钮固定在底部
              Container(
                width: double.infinity,
                color: Colors.white,
                padding: EdgeInsets.all(20),
                child: GetBuilder<FundsController>(
                  builder: (ctrl) {
                    final hasSelection = ctrl.selectedIndex >= 0;
                    final selectedPackage = hasSelection && 
                        ctrl.selectedIndex < ctrl.packagesData.length
                        ? ctrl.packagesData[ctrl.selectedIndex]
                        : null;
                    
                    return ElevatedButton(
                      onPressed: hasSelection ? ctrl.purchasePackage : null,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: hasSelection ? Color(0xFFE33641) : Colors.grey[300],
                        foregroundColor: hasSelection ? Colors.white : Colors.grey[600],
                        minimumSize: Size(double.infinity, 50),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(25),
                        ),
                      ),
                      child: Text(
                        hasSelection 
                            ? '确认支付 ${selectedPackage?.formattedPrice ?? ''}' 
                            : '请选择积分套餐',
                        style: TextStyle(
                          fontSize: 16,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 构建可滚动的历史记录区域
  Widget _buildScrollableHistoryRecords() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        // 标题栏 - 固定在顶部
        Padding(
          padding: EdgeInsets.symmetric(horizontal: 20, vertical: 15),
          child: Row(
            children: [
              Text(
                '积分变更历史',
                style: TextStyle(
                  fontSize: 16,
                  fontWeight: FontWeight.bold,
                ),
              ),
              Spacer(),
              // 加载状态指示器
              GetBuilder<FundsController>(
                builder: (ctrl) => ctrl.isLoadingRecords
                    ? SizedBox(
                        width: 16,
                        height: 16,
                        child: CircularProgressIndicator(
                          strokeWidth: 2,
                          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
                        ),
                      )
                    : SizedBox.shrink(),
              ),
            ],
          ),
        ),
        
        // 可滚动的历史记录列表
        Expanded(
          child: GetBuilder<FundsController>(
            builder: (ctrl) {
              if (ctrl.isLoadingRecords && ctrl.historyData.isEmpty) {
                return Padding(
                  padding: EdgeInsets.symmetric(vertical: 30),
                  child: Center(
                    child: Column(
                      children: [
                        CircularProgressIndicator(
                          valueColor: AlwaysStoppedAnimation<Color>(Color(0xFFE33641)),
                        ),
                        SizedBox(height: 10),
                        Text(
                          '正在加载积分变更历史...',
                          style: TextStyle(color: Colors.grey),
                        ),
                      ],
                    ),
                  ),
                );
              }

              if (ctrl.historyData.isEmpty) {
                return Padding(
                  padding: EdgeInsets.symmetric(vertical: 50),
                  child: Center(
                    child: Column(
                      children: [
                        Icon(Icons.history, size: 48, color: Colors.grey[400]),
                        SizedBox(height: 10),
                        Text(
                          '暂无积分变更记录',
                          style: TextStyle(color: Colors.grey),
                        ),
                        SizedBox(height: 10),
                        ElevatedButton(
                          onPressed: () => ctrl.loadPointsHistory(),
                          child: Text('重新加载'),
                        ),
                      ],
                    ),
                  ),
                );
              }

              return SingleChildScrollView(
                physics: BouncingScrollPhysics(),
                padding: EdgeInsets.symmetric(horizontal: 20),
                child: Column(
                  children: [
                    ListView.separated(
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemCount: ctrl.historyData.length,
                      separatorBuilder: (context, index) => Divider(height: 1),
                      itemBuilder: (context, index) {
                        final record = ctrl.historyData[index];
                        return Padding(
                          padding: EdgeInsets.symmetric(vertical: 15),
                          child: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    record.formattedDate,
                                    style: TextStyle(
                                      fontSize: 14,
                                      color: Colors.black87,
                                    ),
                                  ),
                                  Text(
                                    record.formattedPoints,
                                    style: TextStyle(
                                      fontSize: 14,
                                      fontWeight: FontWeight.bold,
                                      color: record.isIncrease ? Colors.green : Colors.red,
                                    ),
                                  ),
                                ],
                              ),
                              SizedBox(height: 5),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Expanded(
                                    child: Text(
                                      record.changeReason,
                                      style: TextStyle(
                                        fontSize: 13,
                                        color: Colors.grey[600],
                                      ),
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                    ),
                                  ),
                                  Container(
                                    padding: EdgeInsets.symmetric(horizontal: 6, vertical: 2),
                                    decoration: BoxDecoration(
                                      color: record.isIncrease
                                          ? Colors.green.withOpacity(0.1)
                                          : Colors.red.withOpacity(0.1),
                                      borderRadius: BorderRadius.circular(4),
                                    ),
                                    child: Text(
                                      record.changeTypeText,
                                      style: TextStyle(
                                        fontSize: 10,
                                        color: record.isIncrease
                                            ? Colors.green[700]
                                            : Colors.red[700],
                                        fontWeight: FontWeight.w500,
                                      ),
                                    ),
                                  ),
                                ],
                              ),
                            ],
                          ),
                        );
                      },
                    ),
                    SizedBox(height: 20), // 底部间距
                  ],
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<FundsController>(
      init: FundsController(),
      id: "funds",
      builder: (_) {
        return Scaffold(
          backgroundColor: Color(0xFFD46A6A),
          appBar: AppBar(
            leading: IconButton(
              onPressed: () {
                Get.back();
              },
              icon: Icon(Icons.arrow_back_ios_new_outlined, color: Colors.white),
            ),
            title: const Text(
              "资金管理",
              style: TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.bold,
              ),
            ),
            centerTitle: true,
            backgroundColor: Colors.transparent,
            elevation: 0,
            iconTheme: IconThemeData(color: Colors.white),
            systemOverlayStyle: SystemUiOverlayStyle(
              statusBarColor: Colors.transparent,
              statusBarIconBrightness: Brightness.dark, // 使用暗色图标（黑色）
              statusBarBrightness: Brightness.light, // iOS设置
            ),
          ),
          body: SafeArea(
            child: _buildView(),
          ),
        );
      },
    );
  }
}
